<!DOCTYPE html>
<%@ page language="java" import="com.compuvest.web.*,java.util.*,java.io.FileNotFoundException,com.amazon.payments.*,com.amazon.payments.model.*" pageEncoding="UTF-8" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<fmt:setBundle basename="properties.Compuvest" var="cv" scope="page" />

<jsp:useBean id="sb" class="SQLBean" scope="application"/>
<jsp:useBean id="advertShow" class="AdvertShow" scope="application"/>
<jsp:useBean id="basket" class="Basket" scope="session"/>

<%!
    String completeOrder(Basket basket) {

        String orderNumber = "";
        try {
            //Create an Object of create Order which contains the functions for setting Items, Contract Charges and Completing Order
            CBAPurchaseContract lib = new CBAPurchaseContract();

            // shipping Expedet or Standard
            ShippingServiceLevel shipping = ShippingServiceLevel.EXPEDITED;
            if("fdg".equals(basket.getShippingCode()) || "usps".equals(basket.getShippingCode())) {
                shipping = ShippingServiceLevel.STANDARD;
            }

            double grandTotal = 0d;
            List<PurchaseItem> items = new ArrayList<>();
            List<ItemsInBasket> itemsInBasket = basket.getContents();
            for(ItemsInBasket bitem : itemsInBasket) {

                //Create an Item object
                PurchaseItem item = new PurchaseItem();

                grandTotal += bitem.getSellPrice() * bitem.getTotalQuantity();
                //Create an Item Params are MerchantItemId, Title, UnitPriceAmount
                item.createPhysicalItem(bitem.getAccwareCode(), "SKU #" + bitem.getAccwareCode() + " " + bitem.getItemName(), basket.roundTwoDecimals(bitem.getSellPrice()), shipping);
                item.setQuantity(bitem.getTotalQuantity());

                items.add(item);

                if(bitem.getWarrantyTotal() != 0d) {
                    //Create an Item object
                    PurchaseItem warranty = new PurchaseItem();

                    grandTotal += bitem.getWarrantyPrice() * bitem.getTotalQuantity();
                    warranty.createPhysicalItem("W" + bitem.getAccwareCode(), "Extended warranty: " + bitem.getWarrantyDesc() + " for SKU #" + bitem.getAccwareCode(), basket.roundTwoDecimals(bitem.getWarrantyPrice()), shipping);
                    warranty.setQuantity(bitem.getTotalQuantity());

                    items.add(warranty);
                }
            }
            basket.setGrandTotal(grandTotal);

            //Setting Contract Charges Create a Charges object to set charges at contract level.
            ContractCharges chargesObj = new ContractCharges();

            //Set tax at order level
            chargesObj.setContractTax(basket.roundTwoDecimals(basket.getTaxCost())); //make double like 100.00

            //Set shipment charges at Order level
            chargesObj.setContractShippingCharges(basket.roundTwoDecimals(basket.getShippingCost()));

            //Create a promotion
            double promoPrice = basket.getCouponPromotionAmazon(); // use promo code getPromotion
            //System.out.println("grandTotal="+basket.getGrandTotal()+" promoPrice="+promoPrice);
            if(promoPrice != 0d) {
                List<Promotion> contractPromotions = new ArrayList<>();
                contractPromotions.add(new Promotion("Holidy", "Promotion", basket.roundTwoDecimals(promoPrice)));
                PromotionList contractPromotionListObj = new PromotionList(contractPromotions);

                //set Promotion at Order level
                chargesObj.setContractPromotions(contractPromotionListObj);
            }

            //Call the Library function to associate the Contract charges to Amazon purchase contract id
            boolean areContractChargesSet = lib.setContractCharges(basket.getAmazonId(), chargesObj);

            //Call the library function create Order to associate the Items to Amazon PurchaseContract Id
            boolean areItemsSet = lib.setItems(basket.getAmazonId(), items);

            //Check if the call to setItems and  setContract charges where successful
            if(areItemsSet && areContractChargesSet) {
                List<String> orderIdList = lib.completeOrder(basket.getAmazonId(), null, null);//Call completeOrder to complete the Order. This returns the list of Amazon Order Id's
                for(String orderId : orderIdList) {
                    orderNumber = orderId;
                    //System.out.print("OrderId : " + orderId);
                }
            }
        } //Catch the internal exceptions
        catch(CheckoutByAmazonServiceException ex) {
            System.out.println(
                "\nCaught Service Exception: " + ex.getMessage() +
                "\nResponse Status Code: " + ex.getStatusCode() +
                "\nError Code: " + ex.getErrorCode() +
                "\nError Type: " + ex.getErrorType() +
                "\nRequest ID: " + ex.getRequestId() +
                "\nXML: " + ex.getXML());

        } //Catch the request exceptions which will come when there is some error in the inputs passed while calling the API
        catch(CheckoutByAmazonServiceRequestException ex) {
            System.out.println(
                "\nCaught Request Exception: " + ex.getMessage() +
                "\nResponse Status Code: " + ex.getStatusCode() +
                "\nError Code: " + ex.getErrorCode() +
                "\nError Type: " + ex.getErrorType() +
                "\nRequest ID: " + ex.getRequestId() +
                "\nXML: " + ex.getXML());
        } //Catch the exceptions which will come when properties file is not found
        catch(FileNotFoundException ex) {
            System.out.println("Caught Request Exception: " + ex.getMessage());
        }
        return orderNumber;
    }
%>

<%
    // shipping
    String ship = request.getParameter("ship");
    String[] params = ship.split(":");

    basket.setShippingCost(advertShow.getDouble(params[0], 0d));
    basket.setShippingCode(advertShow.getString(params[1], ""));
    basket.setShippingDescription(advertShow.getString(params[2], ""));

    String amazonOrderNumber = completeOrder(basket);
    System.out.println("AmazonNo=" + amazonOrderNumber);

    // write to database amazon orderNo to email
    String orderNumber = "00000000";
    if(amazonOrderNumber.length() != 0) {
        orderNumber = sb.makeAmazonOrder(basket, amazonOrderNumber, advertShow);
    }
%>
<html>
<head>
<title><fmt:message key='webcorp' bundle='${cv}'/> Amazon Thank you</title>
<%@include file="./incl/scripts.txt" %>
<script type='text/javascript' src='https://static-na.payments-amazon.com/cba/js/us/PaymentWidgets.js'></script>
</head>
<body>

<fieldset style='margin:10px 20px;width:400px;'>
  <div class='pr'>
 <div class='bighead'>Thank you for your Order!</div><br/>
You can check the status of your order at your Amazon account or contacting us directly.<br/><br/>
Our phone # 888-644-7017, email: <a href="mailto:<fmt:message key='info' bundle='${cv}'/>"><fmt:message key='info' bundle='${cv}'/></a><br/><br/>
<fmt:message key='webcom' bundle='${cv}'/> Order Number is <tt style="color:green;font-size:20px;"><%= orderNumber %></tt><br/><br/>
<fmt:message key='webcom' bundle='${cv}'/> Team
<br/><br/>
<a class='btlgr' href='<%= session.getAttribute("backItemsPage") == null ? "./" /*application.getInitParameter("http")*/ : (String)session.getAttribute("backItemsPage") %>'>Continue Shopping</a>
</div>

</fieldset>
<%--
<!-- test array -->
    <h3>AmazonOrder Number: <%= amazonOrderNumber %></h3>
    <h3><fmt:message key='webcom' bundle='${cv}'/> Order Number: <%= orderNumber %></h3>
    <ul>
     <li>userInfo: <%= userInfo %></li>
     <li>ship: <%= request.getParameter("ship") %></li>
     <li>param[0]: <%= params[0] %></li>
     <li>param[1]: <%= params[1] %></li>
     <li>param[2]: <%= params[2] %></li>
     <li>tax: <%= basket.getTaxCost() %></li>
    </ul><br/><br/>
    <ul>
<%
            List<ItemsInBasket> itemsInBasket = basket.getContents();
            for(ItemsInBasket bitem : itemsInBasket) {
%>
                <li><%= bitem.getAccwareCode() %> SKU # <%= bitem.getAccwareCode() %>&nbsp;<%= bitem.getItemName() %>&nbsp;<%= basket.roundTwoDecimals(bitem.getSellPrice()) %></li>
<%
                if(bitem.getWarrantyTotal() != 0d) {
%>
                <li><%= "W" + bitem.getAccwareCode() %> Extended warranty:  <%= bitem.getWarrantyDesc() %> for SKU # <%= bitem.getAccwareCode() %>&nbsp;<%= basket.roundTwoDecimals(bitem.getWarrantyTotal()) %></li>
<%
                }
            }
%>
    <li>shipping cost: <%= basket.roundTwoDecimals(basket.getShippingCost()) %></li>
    <li>promotional amazon: <%= basket.roundTwoDecimals(basket.getCouponPromotionAmazon()) %></li>
    </ul>
--%>

<%
    // clean only basket
    basket.clean();
%>

</body>
<!--script type='text/javascript'>
var img = new Image();
img.src = (("http:" == document.location.protocol) ? "http://" : "https://") + 'www.compuvestb2b.com/WebStatus/amazon?pg=3';
</script-->
</html>
